package com.fangfang.home;

import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.common.base.fragment.BaseFragment;
import com.common.bean.InfoResult;
import com.common.image.ImagePreview;
import com.common.image.bean.ImageInfo;
import com.common.image.view.listener.OnBigImageClickListener;
import com.common.image.view.listener.OnBigImageLongClickListener;
import com.common.image.view.listener.OnBigImagePageChangeListener;
import com.common.image.view.listener.OnOriginProgressListener;
import com.common.net.EasyHttp;
import com.common.net.callback.SimpleCallBack;
import com.common.net.exception.ApiException;
import com.common.ui.banner.XBanner;
import com.common.ui.smartrefresh.header.MaterialHeader;
import com.common.ui.smartrefresh.layout.SmartRefreshLayout;
import com.common.ui.smartrefresh.layout.api.RefreshLayout;
import com.common.ui.smartrefresh.layout.footer.ClassicsFooter;
import com.common.ui.smartrefresh.layout.listener.OnLoadMoreListener;
import com.common.ui.smartrefresh.layout.listener.OnRefreshListener;
import com.common.utils.GsonUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fangfang.R;
import com.fangfang.bean.home.BannerBean;
import com.fangfang.bean.home.ContentBean;
import com.fangfang.bean.home.FollowCardBean;
import com.fangfang.bean.home.HeaderBean;
import com.fangfang.bean.home.ItemListBean;
import com.fangfang.bean.home.PictureFollowCardBean;
import com.fangfang.bean.home.SquareCardCollectionBean;
import com.fangfang.bean.home.TextCardBean;
import com.fangfang.bean.home.VideoSmallCardBean;
import com.fangfang.home.adapter.RecommendAdapter;
import com.fangfang.utils.AddressApi;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 推荐
 */
public class RecommendFragment extends BaseFragment {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    private XBanner xbanner;
    private View viewHeadBanner;
    private List<ItemListBean> infos = new ArrayList<>();
    private String nextPageUrl = "";
    private LinearLayoutManager linearLayoutManager;
    ImagePreview.LoadStrategy loadStrategy = ImagePreview.LoadStrategy.Default;
    private List<ImageInfo> imageInfoList = new ArrayList<>();
    private RecommendAdapter recommendAdapter;
    private MaterialHeader materialHeader;
    private ClassicsFooter classicsFooter;

    public static RecommendFragment newInstance() {
        return new RecommendFragment();
    }

    @Override
    public boolean isImmersionBarEnabled() {
        return false;
    }

    @Override
    public View isSupportLoadSirEnabled() {
        return llContent;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_recommend;
    }

    @Override
    public void init() {
        viewHeadBanner = getHeaderViewBanner();
        initBanner(xbanner);
        setBannerDatas();
        initRefresh();
        recommendAdapter = new RecommendAdapter(getActivity(), infos);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(recommendAdapter);
    }

    @Override
    public void loadData() {
        EasyHttp.get(AddressApi.dailyRecommend)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onSuccess(String s) {
                        loadService.showSuccess();
                        parseJson(s);
                    }
                });
       /* RxHttp.get(AddressApi.DAILY) //Get请求
                .asString()
                .as(RxLife.asOnMain(this))
                .subscribe(s -> {
                    //成功回调
                }, throwable -> {
                    //失败回调
                });*/
    }

    @Override
    protected void onSuccess(int what, InfoResult t) {

    }

    @Override
    protected void onFail(int what, InfoResult t) {

    }

    /**
     * 初始化XBanner
     */
    private void initBanner(XBanner banner) {
        //设置广告图片点击事件
        banner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, Object model, View view, int position) {
                Toast.makeText(getActivity(), "点击了第" + (position + 1) + "图片", Toast.LENGTH_SHORT).show();
            }
        });
        //加载广告图片
        banner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                //此处适用Fresco加载图片，可自行替换自己的图片加载框架
                SimpleDraweeView draweeView = (SimpleDraweeView) view;
                BannerBean listBean = ((BannerBean) model);
                String url = listBean.getPath();
                draweeView.setImageURI(Uri.parse(url));
//                加载本地图片展示
//                ((ImageView)view).setImageResource(((LocalImageInfo) model).getXBannerUrl());
            }
        });
    }

    private void setBannerDatas() {
        List<String> paths = new ArrayList<>();
        paths.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1584700877125&di=60533ae9f1a3696ac9fce5da982d4e80&imgtype=0&src=http%3A%2F%2Fpic.feizl.com%2Fupload%2Fallimg%2F170909%2F090051hmf5ju5oy.jpg");
        paths.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1584700877121&di=631f8f3ac8106ba0e06697302d1efc7f&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fpic%2Fc%2F00%2F263e1506139.jpg");
        paths.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1584700877116&di=c2ce8d420822602996da52d4bdeb71a8&imgtype=0&src=http%3A%2F%2Fpic.feizl.com%2Fupload%2Fallimg%2F170903%2F0323sxux4gf3jok.jpg");
        List<BannerBean> bannerBeans = new ArrayList<>();
        for (int i = 0; i < paths.size(); i++) {
            bannerBeans.add(new BannerBean(paths.get(i)));
        }
        //刷新数据之后，需要重新设置是否支持自动轮播
        xbanner.setAutoPlayAble(bannerBeans.size() > 1);
        xbanner.setIsClipChildrenMode(true);
        xbanner.setBannerData(R.layout.layout_fresco_imageview, bannerBeans);
    }

    /**
     * 解析数据
     *
     * @param s json字符串
     */
    private void parseJson(String s) {
        if (!TextUtils.isEmpty(s)) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                nextPageUrl = jsonObject.optString("nextPageUrl", "");
                JSONArray itemList = jsonObject.optJSONArray("itemList");
                String txt = itemList.toString();
                infos = GsonUtils.getInstance().jsonToList(jsonObject.optString("itemList"), ItemListBean.class);
                if (itemList != null) {
                    for (int i = 0; i < itemList.length(); i++) {
                        JSONObject ccurrentObject = itemList.getJSONObject(i);
                        switch (ccurrentObject.optString("type")) {
                            case "squareCardCollection":
                                SquareCardCollectionBean squareCardCollectionBean = new SquareCardCollectionBean();
                                String squareCardCollectionTXT = ccurrentObject.optString("data");
                                JSONObject objectsquareCardCollection = new JSONObject(squareCardCollectionTXT);
                                String headersquareCardCollection = objectsquareCardCollection.optString("header");
                                HeaderBean headerBeanScc = GsonUtils.getInstance().jsonToClass(headersquareCardCollection, HeaderBean.class);

                                squareCardCollectionBean.setHeader(headerBeanScc);

                                List<ItemListBean> infosLeaf = GsonUtils.getInstance().jsonToList(objectsquareCardCollection.optString("itemList"), ItemListBean.class);
                                JSONArray itemListLeaf = objectsquareCardCollection.optJSONArray("itemList");
                                if (itemListLeaf != null) {
                                    for (int j = 0; j < itemListLeaf.length(); j++) {
                                        JSONObject ccurrentObjectLeaf = itemListLeaf.getJSONObject(j);
                                        String txtr = ccurrentObjectLeaf.optString("type");
                                        if(ccurrentObjectLeaf.optString("type").equals("followCard")){
                                            FollowCardBean followCardBean = new FollowCardBean();
                                            String followCardBeanTxt = ccurrentObjectLeaf.optString("data");
                                            JSONObject objectfollowCardBean = new JSONObject(followCardBeanTxt);
                                            String headerTxtfollowCardBean = objectfollowCardBean.optString("header");
                                            HeaderBean headerBeanFC = GsonUtils.getInstance().jsonToClass(headerTxtfollowCardBean, HeaderBean.class);
                                            followCardBean.setHeader(headerBeanFC);
                                            String contentTxtPC = objectfollowCardBean.optString("content");
                                            JSONObject objectContentPC = new JSONObject(contentTxtPC);
                                            String contentDataPC = objectContentPC.optString("data");
                                            ContentBean contentBeanPC = GsonUtils.getInstance().jsonToClass(contentDataPC, ContentBean.class);
                                            followCardBean.setContent(contentBeanPC);
                                            infosLeaf.get(j).setFollowCardBean(followCardBean);
                                            infosLeaf.get(j).setType("followCard");
                                        }
                                    }
                                }
                                squareCardCollectionBean.setItemList(infosLeaf);

                                infos.get(i).setSquareCardCollectionBean(squareCardCollectionBean);
                                infos.get(i).setType("squareCardCollection");
                                break;
                            case "textCard":
                                String textCard = ccurrentObject.optString("data");
                                TextCardBean textCardBean = GsonUtils.getInstance().jsonToClass(textCard, TextCardBean.class);
                                infos.get(i).setTextCardBean(textCardBean);
                                infos.get(i).setType("textCard");
                                break;
                            case "videoSmallCard":
                                String videoSmallCardTxt = ccurrentObject.optString("data");
                                VideoSmallCardBean videoSmallCardBean = GsonUtils.getInstance().jsonToClass(videoSmallCardTxt, VideoSmallCardBean.class);
                                infos.get(i).setVideoSmallCardBean(videoSmallCardBean);
                                infos.get(i).setType("videoSmallCard");
                                break;
                            case "followCard":
                                FollowCardBean followCardBean = new FollowCardBean();
                                String followCardBeanTxt = ccurrentObject.optString("data");
                                JSONObject objectfollowCardBean = new JSONObject(followCardBeanTxt);
                                String headerTxtfollowCardBean = objectfollowCardBean.optString("header");
                                HeaderBean headerBeanFC = GsonUtils.getInstance().jsonToClass(headerTxtfollowCardBean, HeaderBean.class);
                                followCardBean.setHeader(headerBeanFC);
                                String contentTxtPC = objectfollowCardBean.optString("content");
                                JSONObject objectContentPC = new JSONObject(contentTxtPC);
                                String contentDataPC = objectContentPC.optString("data");
                                ContentBean contentBeanPC = GsonUtils.getInstance().jsonToClass(contentDataPC, ContentBean.class);
                                followCardBean.setContent(contentBeanPC);
                                infos.get(i).setFollowCardBean(followCardBean);
                                infos.get(i).setType("followCard");
                                break;
                            case "pictureFollowCard":
                                PictureFollowCardBean pictureFollowCard = new PictureFollowCardBean();
                                String picTxt = ccurrentObject.optString("data");
                                JSONObject objectPic = new JSONObject(picTxt);
                                String headerTxt = objectPic.optString("header");
                                HeaderBean headerBean = GsonUtils.getInstance().jsonToClass(headerTxt, HeaderBean.class);
                                pictureFollowCard.setHeader(headerBean);
                                String contentTxt = objectPic.optString("content");
                                JSONObject objectContent = new JSONObject(contentTxt);
                                String contentData = objectContent.optString("data");
                                ContentBean contentBean = GsonUtils.getInstance().jsonToClass(contentData, ContentBean.class);
                                pictureFollowCard.setContent(contentBean);
                                infos.get(i).setPictureFollowCard(pictureFollowCard);
                                infos.get(i).setType("pictureFollowCard");
                                break;
                            default:
                                break;
                        }
                    }
                }
                setDatas();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void setDatas() {
        recommendAdapter.addData(infos);
        recommendAdapter.addHeaderView(viewHeadBanner);
        recommendAdapter.notifyDataSetChanged();
    }

    private void lookPic() {
        ImagePreview.getInstance()
                // 上下文，必须是activity，不需要担心内存泄漏，本框架已经处理好
                .setContext(getActivity())
                // 从第几张图片开始，索引从0开始哦~
                .setIndex(0)
                //=================================================================================================
                // 有三种设置数据集合的方式，根据自己的需求进行三选一：
                // 1：第一步生成的imageInfo List
                .setImageInfoList(imageInfoList)
                // 2：直接传url List
                //.setImageList(List<String> imageList)
                // 3：只有一张图片的情况，可以直接传入这张图片的url
                //.setImage(String image)
                //=================================================================================================
                // 加载策略，默认为手动模式
                .setLoadStrategy(loadStrategy)
                // 保存的文件夹名称，会在Picture目录进行文件夹的新建。比如："BigImageView"，会在Picture目录新建BigImageView文件夹)
                .setFolderName("BigImageView")
                // 缩放动画时长，单位ms
                .setZoomTransitionDuration(300)
                // 是否启用点击图片关闭。默认启用
                .setEnableClickClose(true)
                // 是否启用下拉关闭。默认不启用
                .setEnableDragClose(true)
                // 是否启用上拉关闭。默认不启用
                .setEnableUpDragClose(true)
                // 是否显示关闭页面按钮，在页面左下角。默认不显示
                .setShowCloseButton(true)
                // 设置关闭按钮图片资源，可不填，默认为库中自带：R.drawable.ic_action_close
                .setCloseIconResId(R.drawable.ic_action_close)
                // 是否显示下载按钮，在页面右下角。默认显示
                .setShowDownButton(true)
                // 设置下载按钮图片资源，可不填，默认为库中自带：R.drawable.icon_download_new
                .setDownIconResId(R.drawable.icon_download_new)
                // 设置是否显示顶部的指示器（1/9）默认显示
                .setShowIndicator(true)
                // 设置失败时的占位图，默认为库中自带R.drawable.load_failed，设置为 0 时不显示
                .setErrorPlaceHolder(R.drawable.load_failed)
                // 点击回调
                .setBigImageClickListener(new OnBigImageClickListener() {
                    @Override
                    public void onClick(View view, int position) {

                    }
                })
                // 长按回调
                .setBigImageLongClickListener(new OnBigImageLongClickListener() {
                    @Override
                    public boolean onLongClick(View view, int position) {
                        return false;
                    }
                })
                // 页面切换回调
                .setBigImagePageChangeListener(new OnBigImagePageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    }

                    @Override
                    public void onPageSelected(int position) {
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                    }
                })

                //=================================================================================================
                // 设置查看原图时的百分比样式：库中带有一个样式：ImagePreview.PROGRESS_THEME_CIRCLE_TEXT，使用如下：
                .setProgressLayoutId(ImagePreview.PROGRESS_THEME_CIRCLE_TEXT, new OnOriginProgressListener() {
                    @Override
                    public void progress(View parentView, int progress) {
                        // 需要找到进度控件并设置百分比，回调中的parentView即传入的布局的根View，可通过parentView找到控件：
                        ProgressBar progressBar = parentView.findViewById(R.id.sh_progress_view);
                        TextView textView = parentView.findViewById(R.id.sh_progress_text);
                        progressBar.setProgress(progress);
                        String progressText = progress + "%";
                        textView.setText(progressText);
                    }

                    @Override
                    public void finish(View parentView) {

                    }
                })

                // 使用自定义百分比样式，传入自己的布局，并设置回调，再根据parentView找到进度控件进行百分比的设置：
                //.setProgressLayoutId(R.layout.image_progress_layout_theme_1, new OnOriginProgressListener() {
                //    @Override public void progress(View parentView, int progress) {
                //        Log.d(TAG, "progress: " + progress);
                //
                //        ProgressBar progressBar = parentView.findViewById(R.id.progress_horizontal);
                //        progressBar.setProgress(progress);
                //    }
                //
                //    @Override public void finish(View parentView) {
                //        Log.d(TAG, "finish: ");
                //    }
                //})
                //=================================================================================================
                // 开启预览
                .start();
    }

    private void initRefresh() {
        //refreshLayout.autoRefresh();//第一次进入触发自动刷新，演示效果
        refreshLayout.setEnableRefresh(true);//是否启用下拉刷新功能
        refreshLayout.setEnableHeaderTranslationContent(false);//是否下拉Header的时候向下平移列表或者内容
        refreshLayout.setEnableLoadMore(false);//是否启用上拉加载功能
        refreshLayout.setEnableFooterTranslationContent(true);//是否上拉Footer的时候向上平移列表或者内容
        refreshLayout.setEnableLoadMoreWhenContentNotFull(true);//是否在列表不满一页时候开启上拉加载功能
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);//是否在全部加载结束之后Footer跟随内容1.0.4
        materialHeader = (MaterialHeader) refreshLayout.getRefreshHeader();
        classicsFooter = (ClassicsFooter) refreshLayout.getRefreshFooter();

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                loadData();
                //refreshLayout.finishRefresh();
                //refreshLayout.resetNoMoreData();//setNoMoreData(false);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                /*refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mAdapter.getItemCount() > 30) {
                            Toast.makeText(getApplication(), "数据全部加载完毕", Toast.LENGTH_SHORT).show();

                        } else {
                            mAdapter.loadMore(initData());
                            refreshLayout.finishLoadMore();
                        }
                    }
                }, 2000);*/
            }
        });
    }

    private View getHeaderViewBanner() {
        View view = getLayoutInflater().inflate(R.layout.head_view_banner,
                (ViewGroup) recyclerView.getParent(), false);
        xbanner = (XBanner) view.findViewById(R.id.xbanner);
        return view;
    }
}
